import config
import bubbles
import time
import os
import sys
from imp import reload
from copy import deepcopy
from pkgutil import walk_packages
from utils import *


class Miraigum:
	def __init__(self):
		self.running = False
		self.blowBubbles()
		self.verify()

	def verify(self):
		with trying():
			post('verify', verifyKey=config.utils.verifyKey)

	def blowBubble(self, finder, name, ispkg):
		flag = name in sys.modules.keys()
		loader = finder.find_module(name)
		mod = loader.load_module(name)
		if flag:
			log('QAQ', name, mod.__spec__)
			reload(mod)
		if hasattr(mod, 'register') and callable(mod.register):
			self.bubbles.append(mod.register())

	def blowBubbles(self):
		self.bubbles = []
		for finder, name, ispkg in walk_packages(config.miraigum.bubbles.paths):
			log('泡泡', name)
			self.blowBubble(finder, name, ispkg)

	def eatBiscuit(self):
		if os.path.exists(config.miraigum.biscuit.path):
			with trying():
				with open(config.miraigum.biscuit.path, 'rb') as f:
					exec(compile(f.read(), config.miraigum.biscuit.path, 'exec'))
				s = config.miraigum.biscuit.succeedMsg
				log(s)
				mail(admin, s)
			with trying():
				os.remove(config.miraigum.biscuit.path)

	def wakeUp(self):
		self.running = True
		while self.running:
			# log('糖糖喵喵叫~')
			time.sleep(config.miraigum.sleepingSeconds)
			self.eatBiscuit()
			with trying():
				self.chat()

	def chat(self):
		# log('糖糖在倾听……')
		res = get(par('fetchMessage', count=10))
		while res['code'] == 4:
			log('mirai连接中……')
			self.verify()
			res = get(par('fetchMessage', count=10))
		msgs = res['data']
		# log('糖糖在吹泡泡')
		for bub in self.bubbles:
			with trying():
				if bub.type == 'active':
					bub.run(self)
				elif bub.type == 'passive':
					for msg in msgs:
						cpy = deepcopy(msg)
						bub.run(self, cpy)

	def sleep(self):
		self.running = False
